package cn.thens.kdroid.upay


import android.app.Activity
import com.alipay.sdk.app.PayTask
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

@Suppress("unused", "SpellCheckingInspection")
object Alipay : Payment {
    private const val CODE_SUCCESS = "9000"
    private const val CODE_CANCEL = "6001"
    private const val CODE_FAIL = "4000"

    override fun pay(activity: Activity, orderInfo: String): Observable<PayResult> {
        return Observable
                .create<PayResult> {
                    val payResult = PayTask(activity).payV2(orderInfo, true)
                    val status = payResult["resultStatus"]
                    val description = payResult["memo"]
                    it.onNext(when (status) {
                        CODE_SUCCESS -> PayResult(PayResult.SUCCESS, "$status: 支付成功")
                        CODE_CANCEL -> PayResult(PayResult.CANCEL, "$status: 支付已取消")
                        CODE_FAIL -> PayResult(PayResult.FAIL, "$status: $description")
                        else -> PayResult(PayResult.FAIL, "$status: $description")
                    })
                    it.onComplete()
                }
                .onErrorReturn { PayResult(PayResult.FAIL, "支付失败: ${it.message}") }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
    }
}